package com.gegong.imr.client.tasks.vbox;


import com.alibaba.fastjson.JSONArray;
import com.gegong.imr.client.IMessageClientProfiles;
import com.gegong.imr.client.bean.VmStatus;
import com.gegong.imr.client.config.ImrCenterConfig;
import com.gegong.imr.client.tasks.AbstractReportStatusTask;
import com.gegong.imr.client.utils.http.HttpRequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import org.virtualbox_5_2.VirtualBoxManager;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用于上报客户端机相关状态
 *
 * @author dongjak
 */

@Component
@Slf4j
@Profile(IMessageClientProfiles.VBOX)
public class VboxReportStatusTask extends AbstractReportStatusTask {

    private final VirtualBoxManager virtualBoxManager;
    private final ImrCenterConfig centerConfig;

    @Autowired
    public VboxReportStatusTask(VirtualBoxManager virtualBoxManager, ImrCenterConfig centerConfig) {
        this.virtualBoxManager = virtualBoxManager;
        this.centerConfig = centerConfig;
    }

    @Override
    public void run() {
        try {
            log.info("上报客户端状态...");
            List<VmStatus> clientStatuses = virtualBoxManager.getVBox().getMachines().stream().map(VmStatus::fromVbox).collect(Collectors.toList());
            HttpRequestUtils.postJsonWithJsonRes(centerConfig.urlForReportClientStatus(), JSONArray.toJSONString(clientStatuses));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
